import request from './useRequests';
import { userinfo } from '@/stores/counter';
import { ElMessage } from 'element-plus';
import getStatus from '@/api/getStatus';
import type { BaseInfo } from '@/stores/counter';
import getUserInfo from '@/api/loadUserInfo';
import subscribeCate from './subscribeCate';
export default function uselogin() {
  const { getSubscribeList } = subscribeCate();
  // const { status } = getStatus();
  const { getInfo, setInfo } = getUserInfo();
  const user = userinfo();
  async function login(username: string, passwd: string) {
    if (username == undefined || passwd == undefined) {
      ElMessage({
        showClose: true,
        message: '不能输入空字符',
        type: 'error',
      });
      return 0;
    }
    try {
      let res = await request.post('/user/login', {
        username: username,
        password: passwd,
      });
      res = res.data;
      if (res.status) {
        ElMessage({
          showClose: true,
          message: '登录成功',
          type: 'success',
        });
        const userinfo: BaseInfo = {
          id: res.data.id,
          username: res.data.username,
          telephone: res.data.phone,
          token: res.data.token,
          sex: res.data.sex,
          avator: res.data.avator,
          mail: res.data.mail,
        };
        getInfo(userinfo);
        setInfo();
        getSubscribeList();
      } else {
        ElMessage({
          showClose: true,
          message: '用户名或密码错误',
          type: 'error',
        });
      }
    } catch (err: any) {
      ElMessage({
        showClose: true,
        message: '登录时发生未知错误',
        type: 'error',
      });
    }
  }

  return {
    login,
  };
}
